﻿using System;
using System.Data;
using viForum.Classes;
using viForum.Providers;
using visinia.SmartEngine.Cache;

namespace viForum.Controllers
{
    public class UserController
    {

        //public static void AddUser(object UserName, EventArgs e)
        //{
        //    //User user = GetUser((string) UserName);
        //    //if (user == null)
        //        AddUser(new User((string)UserName, 0));
        //}

        public static void DeleteUser(object UserName, EventArgs e)
        {
            User user = GetUser((string)UserName);
            if (user != null)
                DeleteUser(user);
        }


        #region CACHE KEYS
        private const string KEY_USER = "vf_user_{0}";
        #endregion

        public static User GetUser(string UserName)
        {
            string key = string.Format(KEY_USER, UserName);
            User user = (User)DataCache.GetCache(key);
            if (user == null)
            {
                user = FillUser(viForumDataProvider.Provider.GetUser(UserName));
                DataCache.SetCache(key, user);
            }
            return user;
        }

        private static User FillUser(IDataReader dr)
        {
            while (dr.Read())
            {
                return ActualRead(dr);
            }
            dr.Close();
            return null;
        }

        private static User ActualRead(IDataReader dr)
        {
            User user = new User();
            if (dr["UserName"] != Convert.DBNull)
                user.UserName = (string)dr["UserName"];
            if (dr["PostsCount"] != Convert.DBNull)
                user.PostsCount = (int)dr["PostsCount"];
            return user;
        }

        public static void AddUser(User user)
        {
            viForumDataProvider.Provider.AddUser(user.UserName, user.PostsCount);
            DataCache.DeleteCacheMultiple("vf_user");
        }

        public static void DeleteUser(User user)
        {
            viForumDataProvider.Provider.DeleteUser(user.UserName);
            DataCache.DeleteCacheMultiple("vf_user");
        }

        public static void UpdateUser(User user)
        {
            viForumDataProvider.Provider.UpdateUser(user.UserName, user.PostsCount);
            DataCache.DeleteCacheMultiple("vf_user");
        }
    }
}
